package service.impl;


import dao.CommunityDao;
import dao.impl.CommunityDaoImpl;
import entity.Community;
import service.CommunityService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommunityServiceImpl implements CommunityService {

    CommunityDao communityDao = new CommunityDaoImpl();

    public Map<String, Object> searchAll(int page,int limit) {

        Map<String, Object> result = new HashMap<>();

        List<Community> list = communityDao.getAllcommunity(page, limit);
        int count = communityDao.getCountByCommunity();
        System.out.println(count);
        result.put("data",list);
        result.put("count",count);
        result.put("code",0);
        return result;
    }


    public Map<String,Object> saveCommunity(Community household) {
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            if(!communityDao.select(household)){
                map.put("success",communityDao.insert(household));
                map.put("msg", "插入成功");
            }else {
                map.put("success", communityDao.update(household));
                map.put("msg", "修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "操作失败!");
        }
        return map;
    }

    public Map<String,Object> deleteCommunity(String id){

        Map<String,Object> map=new HashMap();
        String[] strs = id.split(",");

        List<Integer> list = new ArrayList<>();

        for(int i = 0;i < strs.length;i ++){
            list.add(Integer.parseInt(strs[i]));
        }
        if(list.size() > 1 ){
            if (communityDao.deleteByIds(list)){
                map.put("success",true);
                map.put("msg", "批量删除成功");
            }
            else {
                map.put("success",false);
                map.put("msg", "批量删除失败");
            }
        }else if(list.size() == 1 ){
            if (communityDao.deleteById(list)){
                map.put("success",true);
                map.put("msg", "删除成功");
            }
            else{
                map.put("success",false);
                map.put("msg", "删除失败");
            }
        }

        return map;
    }
}


